<template>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="650px"
    append-to-body
    @close="clearDataList()"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="160px"
    >
      <el-row>
        <el-col :span="19" style="">
          <el-form-item label="人员" prop="ryCode">
            <div
              style="
                width: 100%;
                border: 1px solid #c0c4cc;
                height: 97px;
                background: #f4f4f8;
                border-radius: 5px;
                padding: 10px;
                overflow-y: scroll;
              "
            >
              <span v-for="(item, index) in chooseList" :key="index"
                >{{ item.ryName }}、</span
              >
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="5" v-if="!options">
          &nbsp;&nbsp;&nbsp;<el-button @click="selectCheckUser">选择</el-button>
        </el-col>
      </el-row>
      <el-form-item label="奖金项名称" prop="jjxId">
        <el-select
          :clearable="true"
          v-model="dataForm.jjxId"
          @change="elChange"
          placeholder="请选择"
          class="xiaLa"
          style="width: 90%"
        >
          <el-option
            v-for="(item, index) in jjxOptions"
            :key="index"
            :label="item.jjxMc"
            :value="item.jjxId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="奖金金额" prop="jjJe">
        <el-input-number
          v-model="dataForm.jjJe"
          :precision="2"
          :step="1"
          :min="0"
          style="width: 200px"
        ></el-input-number>
        &nbsp;<span style="color: orange" v-show="this.surplusValue !== ''"
          >奖金金额剩余{{ surplusValue }}元</span
        >
      </el-form-item>
      <el-form-item label="是否允许下级查看">
        <el-switch
          v-model="dataForm.showDx"
          active-text="是"
          inactive-text="否"
          active-value="1"
          inactive-value="0"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="奖金说明" prop="jjSm">
        <el-input
          v-model="dataForm.jjSm"
          placeholder="奖金说明"
          :rows="3"
          type="textarea"
          style="width: 90%"
        ></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="dataFormSubmit()" v-if="canSubmit"
        >确定</el-button
      >
      <el-button type="primary" plain @click="clearDataList">取消</el-button>
    </span>
    <!--选择人员-->
    <check-user
      ref="checkUser"
      :multiple="false"
      :userIds="userIds"
      @getUserList="getUserRoleList"
    ></check-user>
  </el-dialog>
</template>

<script>
import { addObj } from "@/api/jiangjin/jiangjinfpjjfpgrdxb";
import { getBmfpListNoRepeat } from "@/api/jiangjin/jiangjinfpjjbmfppzmxb";
import { getJjDeptJjx } from "@/api/jiangjin/jiangjinjjxxxb";
import { getObj, putObj } from "@/api/jiangjin/jiangjinfpjjfpdjb";
import checkUser from "./personRyxxb";

export default {
  name: "jiangjinfpjjfpdjb-fp-dxfp-form",
  components: {
    checkUser,
  },
  data() {
    const checkAmount = (rule, value, callback) => {
      // callback(new Error(value));

      if (this.dataForm.jjxId) {
        const strJjXq = JSON.parse(this.jjfpdjb.jjxJeXq);
        const objJjXq = strJjXq[this.dataForm.jjxId];

        // if (this.jjfpdjb.sfCeff != "是") {
        //   if (objJjXq.jjYe < value) {
        //     // callback(new Error('奖金金额大于奖金余额,奖金余额剩'+objJjXq.jjYe));
        //     callback(new Error("奖金金额大于奖金余额"));
        //   } else {
        //     callback();
        //   }
        // } else {
        //   callback();
        // }
        callback();
      } else {
        // callback(new Error("出错啦"));
        callback();
      }
    };
    const perCheck = (rule, value, callback) => {
      if ((this.chooseList.length = 0)) {
        callback(new Error("人员名称不能为空"));
      } else {
        callback();
      }
    };
    return {
      visible: false,
      canSubmit: false,
      title: "新增",
      jjxOptions: [],
      userIds: [],
      deptId: "",
      //奖金分配Id
      jjfpId: "",
      //主表记录
      jjfpdjb: [],
      //奖金部门分配配置明细表
      jjbmfppzmxb: [],
      //奖金项余额
      surplusValue: "",
      dataForm: {
        id: 0,
        jjDeptId: "",
        fpId: "",
        bmjjFpId: "",
        fpDeptId: "",
        fpDeptCode: "",
        fpDeptName: "",
        jjxId: "",
        jjxMc: "",
        jjJe: "",
        jjSm: "",
        showDx: "1",
      },
      options: {},
      chooseList: [],
      dataRule: {
        ryCode: [
          {
            required: true,
            message: "人员名称不能为空",
            trigger: "blur",
            validator: perCheck,
          },
        ],
        fpDeptId: [
          { required: true, message: "分配部门不能为空", trigger: "blur" },
        ],
        jjxId: [{ required: true, message: "奖金项不能为空", trigger: "blur" }],
        jjJe: [
          { required: true, message: "奖金金额不能为空", trigger: "blur" },
          { validator: checkAmount, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    elChange(value) {
      if (value === "") {
        this.surplusValue = "";
        return;
      }
      const strJjXq = JSON.parse(this.jjfpdjb.jjxJeXq);
      this.surplusValue = strJjXq[value].jjYe;
    },
    //取得空值 增加弹错判断
    getBlankValue(value) {
      let lResult = "";
      if (value === undefined || value === null) {
      } else {
        lResult = value;
      }
      return lResult;
    },
    selectCheckUser() {
      this.userIds = [];
      this.userIds.push(this.getBlankValue(this.dataForm.ryCode));
      //防止数据慢于页面加载
      this.$nextTick(() => {
        this.$refs.checkUser.init(this.chooseList);
      });
    },
    getUserRoleList(data) {
      this.chooseList=[]
      data.forEach((item) => {
        var item = {
          ryCode: item.ryCode,
          ryName: item.ryXm,
          deptId: item.rySjdwId,
          deptCode: item.rySjdwCode,
          deptName: item.rySjdw,
          ryZhiwei: item.ryZhiwei,
          ryZwjb:item.ryZwjb,
          userId:item.userId
        };
        this.chooseList.push(item);

        this.dataForm.userList = JSON.stringify(this.chooseList);
      });
    },
    init(jjfpId, deptId, row) {
      this.options = undefined;
      this.options = row;
      if (this.options != undefined) {
        this.title = "修改";
        this.dataForm = row;
      }
      this.deptId = "";
      this.jjfpId = "";

      this.visible = true;
      this.canSubmit = true;
      this.deptId = deptId;
      this.jjfpId = jjfpId;

      // 1.取记录 2.设置初始值
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        this.dataForm.fpId = this.jjfpId;
        // 部门奖金分配ID 不处理
        // this.dataForm.bmjjFpId = 0;

        //取得主表
        getObj(jjfpId).then((response) => {
          console.log(response.data.data);
          this.jjfpdjb = [];
          this.jjfpdjb = response.data.data;
          this.jjDeptId = this.jjfpdjb.jjDeptId;
          this.$set(this.dataForm, "jjDeptId", this.jjfpdjb.jjDeptId);

          // 取得奖金项
          const xData = JSON.parse(this.jjfpdjb.detailJson);
          this.jjxOptions = [];
          this.jjxOptions = xData;
        });

        //奖金部门分配配置明细表
        getBmfpListNoRepeat(jjfpId).then((res) => {
          this.jjbmfppzmxb = [];
          this.jjbmfppzmxb = res.data.data;
          ////console.log(this.jjbmfppzmxb);
        });
      });
    },
    //去重复
    unique(arr1) {
      const res = new Map();
      return arr1.filter((a) => !res.has(a.level) && res.set(a.level, 1));
    },
    uniqueFun(arr, type) {
      const res = new Map();
      return arr.filter((a) => !res.has(a[type]) && res.set(a[type], 1));
    },
    //设置字段
    setColumns() {
      //设置分配字段
      this.jjbmfppzmxb.find((item) => {
        if (item.deptId === this.dataForm.fpDeptId) {
          this.$set(this.dataForm, "fpDeptCode", item.deptCode);
          this.$set(this.dataForm, "fpDeptName", item.deptName);
        }
      });
      // 设置奖金项
      this.jjxOptions.find((item) => {
        if (item.jjxId === this.dataForm.jjxId) {
          this.$set(this.dataForm, "jjxMc", item.jjxMc);
          this.$set(this.dataForm, "jjxRq", item.jjxDate);
          this.$set(this.dataForm, "jjxBh", item.jjxBh);
        }
      });

      //计算
      const strJjXq = JSON.parse(this.jjfpdjb.jjxJeXq);
      const objJjXq = strJjXq[this.dataForm.jjxId];

      this.$set(objJjXq, "dxFp", objJjXq["dxFp"] + this.dataForm.jjJe);
      this.$set(objJjXq, "jjYe", objJjXq["jjYe"] - this.dataForm.jjJe);

      this.jjfpdjb.jjxJeXq = JSON.stringify(strJjXq);
      ////console.log(this.jjfpdjb.jjxJeXq);

      this.$set(
        this.jjfpdjb,
        "dxFp",
        this.jjfpdjb["dxFp"] + this.dataForm.jjJe
      );
      this.$set(this.jjfpdjb, "jjYe", this.jjfpdjb.jjYe - this.dataForm.jjJe);
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.setColumns();
          this.canSubmit = false;
          this.dataForm.showDx = this.dataForm.showDx * 1;
          addObj(this.dataForm)
            .then((data) => {
              putObj(this.jjfpdjb)
                .then((data) => {
                  this.$notify.closeAll();
                  this.$notify.success("添加成功");
                  this.visible = false;
                  this.$emit("refreshDataList");
                })
                .catch(() => {
                  this.canSubmit = true;
                });
            })
            .catch(() => {
              this.canSubmit = true;
            });
        }
      });
    },
    //清空记录
    clearDataList() {
      this.visible = false;

      this.jjxOptions = [];
      this.userIds = [];
      this.deptId = "";
      //奖金分配Id
      this.jjfpId = "";
      //主表记录
      this.jjfpdjb = [];
      //奖金部门分配配置明细表
      this.jjbmfppzmxb = [];
      this.dataForm = {
        id: 0,
        jjDeptId: "",
        fpId: "",
        bmjjFpId: "",
        fpDeptId: "",
        fpDeptCode: "",
        fpDeptName: "",
        deptId: "",
        deptCode: "",
        deptName: "",
        ryCode: "",
        ryName: "",
        jjxId: "",
        jjxMc: "",
        jjJe: "",
        jjSm: "",
        showDx: "1",
      };
    },
  },
};
</script>

<style scoped>
</style>
